using System;
using System.Collections.Generic;
using System.Text;

using HandyIRCCore;

namespace HandyIRCChat
{
    // Only one instance of ConsoleObj can be created (singleton pattern)
    // todo: if was not called ReleaseInstance exception must be generated
    public class ConsoleObject
    {
        #region Singleton pattern management

        private static ConsoleObject instance;

        private ConsoleObject(HandyLogic hl, Core c)
        {
            handyLogic = hl;
            ircCore = c;

            ircCore.ReceiveMessageEvent += new Core.ReceiveMessageEventHandler(ircCore_ReceiveMessageEvent);
        }

        public static ConsoleObject CreateInstance(HandyLogic hl, Core c)
        {
            // "lazy initialization"
            if (instance == null)
            {
                instance = new ConsoleObject(hl, c);
            }

            return instance;
        }

        public static void ReleaseInstance()
        {
            if (instance != null)
            {
                instance.OnReleaseInstance();

                instance = null;
            }
        }

        #endregion

        #region Declarations

        private const int bufferMaxLength = 4096;

        // Length cannot be greater than bufferMaxLength
        private string messageBuffer = "";

        private HandyLogic handyLogic;

        private Core ircCore;

        public event ConsoleMessageEventHandler ConsoleMessageEvent;

        public event ReleaseInstanceEventHandler ReleaseInstanceEvent;

        public delegate void ConsoleMessageEventHandler(object sender, 
                                                        string message);

        public delegate void ReleaseInstanceEventHandler(object sender);

        #endregion

        #region Properties

        public string MessageBuffer
        {
            get
            {
                return messageBuffer;
            }
        }

        #endregion

        #region Methods

        public void SendMessage(string message)
        {
            if (handyLogic.IsConnected)
                ircCore.SendMessage(message);
        }

        private void ircCore_ReceiveMessageEvent(object sender, HandyIRCMessage msg)
        {
            StringBuilder sb = new StringBuilder(messageBuffer);

            sb.Append(msg.RawMessage + Environment.NewLine);
            if (sb.Length > bufferMaxLength)
            {
                sb.Remove(0, sb.Length - bufferMaxLength);
            }

            messageBuffer = sb.ToString();

            if (ConsoleMessageEvent != null)
                ConsoleMessageEvent(this, msg.RawMessage);
        }

        private void OnReleaseInstance()
        {
            if (ReleaseInstanceEvent != null)
                ReleaseInstanceEvent(this);
        }

        #endregion
    }
}
